<?php

namespace plugin\ycMassage\utils\notice;

use plugin\ycMassage\app\model\MassageWinnerlookPrivacy;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\WinnerlookChannels;
use plugin\ycMassage\utils\Sms;
use plugin\ycMassage\utils\WechatHelper;
use plugin\ycMassage\utils\Yunxin;
use think\facade\Log;

class Notice
{
    public $dev = false;
    public $saas_appid;
    public $type;
    public $role = ['ADMIN', 'TECHNICIAN', 'USER'];
    public $TECHNICIAN = [
        'mobile' => [],
        'wx' => [],
    ];
    public $USER = [
        'mobile' => [],
        'wx' => [],
    ];
    public $data = [];
    public $domain = '';
    public function setData($data)
    {
        $this->data = $data;
        return $this;
    }
    public function sendADMIN()
    {
        $config = getHpConfig($this->type, $this->saas_appid, 'notice_admin');
        if (isset($config['state']) && $config['state']) {
            if (!empty($config['mobile'])) {
                foreach ($config['mobile'] as $mobile) {
                    $sms_template='';
                    try {
                        $sms_template=$config['sms_template'];
                        $typeValue = NoticeType::getText($this->type);
                        $template = $typeValue['sms_template']['admin'];
                        foreach ($this->data as $key => $value) {
                            $template = str_replace('${' . $key . '}', $value, $template);
                        }
                        Sms::send($this->saas_appid, $mobile, $sms_template, $template, $this->data);
                    } catch (\Throwable $th) {
                        Log::error("管理员短信({$sms_template})通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
            if (!empty($config['voice_mobile'])) {
                $templateArgs=[];
                switch ($this->type) {
                    case NoticeType::ALARM['value']:
                        $templateArgs=[
                            'var1'=>$this->data['role'],
                            'var2'=>$this->data['name']
                        ];
                        break;
                        case NoticeType::WORK_ORDER['value']:
                    case NoticeType::FEEDBACK['value']:
                        break;
                    case NoticeType::ORDERS_PAY['value']:
                        $templateArgs=[
                            'var1'=>$this->data['time'],
                        ];
                        break;
                    case NoticeType::TECHNICIAN_DEPARTURE['value']:
                        $templateArgs=[
                            'var1'=>MassageReplaceIndustryPersonnelName($this->saas_appid,'技师'),
                        ];
                        break;
                    case NoticeType::TECHNICIAN_ARRIVAL['value']:
                        $templateArgs=[
                            'var1'=>MassageReplaceIndustryPersonnelName($this->saas_appid,'技师'),
                        ];
                        break;
                    case NoticeType::TECHNICIAN_VERIFICATION['value']:
                    case NoticeType::SERVICE_START['value']:
                    case NoticeType::SERVICE_END['value']:
                        break;
                    case NoticeType::REFUND['value']:
                        break;
                    case NoticeType::EXAMINE['value']:
                        break;
                    case NoticeType::TRANSFERRING['value']:
                        $templateArgs=[
                            'var1'=>$this->data['state']
                        ];
                        break;
                }
                foreach ($config['voice_mobile'] as $mobile) {
                    $voice_template='';
                    try {
                        $voice_template=$config['voice_template'];
                        $typeValue = NoticeType::getText($this->type);
                        $template = $typeValue['voice_template']['admin'];
                        $MassageWinnerlookPrivacy=MassageWinnerlookPrivacy::getFindNumber($this->saas_appid, WinnerlookChannels::VOICE_SERVICE['value']);
                        $return_url = "{$this->domain}/app/ycMassage/Notify/winnerlook?appid={$this->saas_appid}";
                        $Yunxin=new Yunxin($this->saas_appid);
                        $data=[
                            'displayNumber' => $MassageWinnerlookPrivacy->tel,
                            'calleeNumber' => $mobile,
                            'templateID' => $voice_template,
                            'templateArgs' => $templateArgs,
                            'replayTimes'=>2,
                            'callbackUrl'=>$return_url,
                            // 'customerData'=>''
                        ];
                        $Yunxin->notify($data);
                    } catch (\Throwable $th) {
                        Log::error("管理员语音({$voice_template})通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
            if (!empty($config['wx'])) {
                foreach ($config['wx'] as $wx) {
                    try {
                        $this->sendWx($wx['openid'], "{$this->domain}/app/ycMassage/admin/#/?appid={$this->saas_appid}");
                    } catch (\Throwable $th) {
                        Log::error('管理员微信通知失败：'.$th->getMessage());
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
        }
    }
    public function sendWx($openid, $url)
    {
        $data = [
            'touser' => $openid,
        ];
        switch ($this->type) {
            case NoticeType::WORK_ORDER['value']:
            case NoticeType::ALARM['value']:
            case NoticeType::FEEDBACK['value']:
                $template_id = getHpConfig('work_order_template_id', $this->saas_appid, 'wx');
                if ($template_id) {
                    $data['template_id'] = $template_id;
                    $data['data'] = [
                        'thing4' => [
                            'value' => $this->data['service_name']
                        ],
                        'thing11' => [
                            'value' => $this->data['name']
                        ],
                        'time16' => [
                            'value' => $this->data['time']
                        ],
                    ];
                }
                break;
            case NoticeType::ORDERS_PAY['value']:
                $template_id = getHpConfig('order_state_template_id', $this->saas_appid, 'wx');
                if ($template_id) {
                    $data['template_id'] = $template_id;
                    $data['data'] = [
                        # 产品名称
                        'thing8' => [
                            'value' => $this->data['title']
                        ],
                        # 订单编号
                        'character_string2' => [
                            'value' => $this->data['trade']
                        ],
                        # 客户名称
                        'thing1' => [
                            'value' => $this->data['name']
                        ],
                        # 付款金额
                        'amount10' => [
                            'value' => $this->data['price']
                        ],
                        # 支付时间
                        'time4' => [
                            'value' => $this->data['create_time']
                        ],
                    ];
                }
                break;
            case NoticeType::TECHNICIAN_DEPARTURE['value']:
            case NoticeType::TECHNICIAN_ARRIVAL['value']:
            case NoticeType::TECHNICIAN_VERIFICATION['value']:
            case NoticeType::SERVICE_START['value']:
            case NoticeType::SERVICE_END['value']:
                $template_id = getHpConfig('service_state_template_id', $this->saas_appid, 'wx');
                if ($template_id) {
                    $data['template_id'] = $template_id;
                    $data['data'] = [
                        # 工单状态
                        'thing3' => [
                            'value' => $this->data['state'],
                            'color' => '#f56c6c'
                        ],
                        # 项目名称
                        'thing19' => [
                            'value' => $this->data['title']
                        ],
                        # 工单号
                        'character_string11' => [
                            'value' => $this->data['as_id']
                        ],
                        # 客户名称
                        'thing16' => [
                            'value' => $this->data['name']
                        ],
                        # 处理人
                        'thing17' => [
                            'value' => $this->data['technician']
                        ],
                    ];
                }
                break;
            case NoticeType::REFUND['value']:
                $template_id = getHpConfig('refund_template_id', $this->saas_appid, 'wx');
                if ($template_id) {
                    $data['template_id'] = $template_id;
                    $data['data'] = [
                        # 订单编号
                        'character_string12' => [
                            'value' => $this->data['trade']
                        ],
                        # 支付金额
                        'amount9' => [
                            'value' => $this->data['price']
                        ],
                        # 退款金额
                        'amount4' => [
                            'value' => $this->data['refund_price']
                        ],
                        # 退款时间
                        'time7' => [
                            'value' => $this->data['time']
                        ],
                        # 退款人
                        'thing10' => [
                            'value' => $this->data['name']
                        ],
                    ];
                }
                break;
            case NoticeType::EXAMINE['value']:
                $template_id = getHpConfig('examine_template_id', $this->saas_appid, 'wx');
                if ($template_id) {
                    $data['template_id'] = $template_id;
                    $data['data'] = [
                        # 单据名称
                        'thing2' => [
                            'value' => $this->data['type']
                        ],
                        # 单据编号
                        'thing3' => [
                            'value' => $this->data['trade']
                        ],
                        # 单据状态
                        'thing4' => [
                            'value' => $this->data['state']
                        ],
                        # 退回原因
                        'thing8' => [
                            'value' => $this->data['result']
                        ],
                        # 退回日期
                        'time6' => [
                            'value' => $this->data['time']
                        ],
                    ];
                }
                break;
            case NoticeType::TRANSFERRING['value']:
                $template_id = getHpConfig('transferring_template_id', $this->saas_appid, 'wx');
                if ($template_id) {
                    $data['template_id'] = $template_id;
                    $data['data'] = [
                        # 订单号
                        'character_string3' => [
                            'value' => $this->data['trade']
                        ],
                        # 修改项目
                        'thing7' => [
                            'value' => $this->data['state']
                        ],
                        # 客户名称
                        'thing8' => [
                            'value' => $this->data['name']
                        ],
                        # 出发时间
                        'time6' => [
                            'value' => $this->data['time']
                        ],
                    ];
                }
                break;
        }
        if (isset($data['template_id'])) {
            $data['url'] = $url;
            WechatHelper::templateSend($this->saas_appid, $data);
        }
    }
    public function sendTECHNICIAN()
    {
        $config = getHpConfig($this->type, $this->saas_appid, 'notice_technician');
        if (isset($config['state']) && $config['state']) {
            if (isset($config['mobile']) && $config['mobile']) {
                foreach ($this->TECHNICIAN['mobile'] as $mobile) {
                    if (!$mobile) {
                        continue;
                    }
                    $sms_template='';
                    try {
                        $sms_template=$config['sms_template'];
                        $typeValue = NoticeType::getText($this->type);
                        $template = $typeValue['sms_template']['technician'];
                        foreach ($this->data as $key => $value) {
                            $template = str_replace('${' . $key . '}', $value, $template);
                        }
                        Sms::send($this->saas_appid, $mobile, $sms_template, $template, $this->data);
                    } catch (\Throwable $th) {
                        Log::error("技师短信({$sms_template})通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
            if (isset($config['voice_mobile']) && $config['voice_mobile']) {
                $templateArgs=[];
                switch ($this->type) {
                    case NoticeType::ALARM['value']:
                        $templateArgs=[
                            'var1'=>$this->data['role'],
                            'var2'=>$this->data['name']
                        ];
                        break;
                        case NoticeType::WORK_ORDER['value']:
                    case NoticeType::FEEDBACK['value']:
                        break;
                    case NoticeType::ORDERS_PAY['value']:
                        $templateArgs=[
                            'var1'=>$this->data['time'],
                        ];
                        break;
                    case NoticeType::TECHNICIAN_DEPARTURE['value']:
                        $templateArgs=[
                            'var1'=>MassageReplaceIndustryPersonnelName($this->saas_appid,'技师'),
                        ];
                        break;
                    case NoticeType::TECHNICIAN_ARRIVAL['value']:
                        $templateArgs=[
                            'var1'=>MassageReplaceIndustryPersonnelName($this->saas_appid,'技师'),
                        ];
                        break;
                    case NoticeType::TECHNICIAN_VERIFICATION['value']:
                    case NoticeType::SERVICE_START['value']:
                    case NoticeType::SERVICE_END['value']:
                        break;
                    case NoticeType::REFUND['value']:
                        break;
                    case NoticeType::EXAMINE['value']:
                        break;
                    case NoticeType::TRANSFERRING['value']:
                        $templateArgs=[
                            'var1'=>$this->data['state']
                        ];
                        break;
                }
                foreach ($this->TECHNICIAN['mobile'] as $mobile) {
                    if (!$mobile) {
                        continue;
                    }
                    $voice_template='';
                    try {
                        $voice_template=$config['voice_template'];
                        $typeValue = NoticeType::getText($this->type);
                        $template = $typeValue['voice_template']['technician'];
                        $MassageWinnerlookPrivacy=MassageWinnerlookPrivacy::getFindNumber($this->saas_appid, WinnerlookChannels::VOICE_SERVICE['value']);
                        $return_url = "{$this->domain}/app/ycMassage/Notify/winnerlook?appid={$this->saas_appid}";
                        $Yunxin=new Yunxin($this->saas_appid);
                        $data=[
                            'displayNumber' => $MassageWinnerlookPrivacy->tel,
                            'calleeNumber' => $mobile,
                            'templateID' => $voice_template,
                            'templateArgs' => $templateArgs,
                            'replayTimes'=>2,
                            'callbackUrl'=>$return_url,
                            // 'customerData'=>''
                        ];
                        $Yunxin->notify($data);
                    } catch (\Throwable $th) {
                        Log::error("技师语音({$voice_template})通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
            if (isset($config['wx']) && $config['wx']) {
                foreach ($this->TECHNICIAN['wx'] as $openid) {
                    if (!$openid) {
                        continue;
                    }
                    try {
                        $this->sendWx($openid, "{$this->domain}/app/ycMassage/#/technician/pages/index/index?appid={$this->saas_appid}");
                    } catch (\Throwable $th) {
                        Log::error('技师微信通知失败：'.$th->getMessage());
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
        }
    }
    public function sendUSER()
    {
        $config = getHpConfig($this->type, $this->saas_appid, 'notice_user');
        if (isset($config['state']) && $config['state']) {
            if (isset($config['mobile']) && $config['mobile']) {
                foreach ($this->USER['mobile'] as $mobile) {
                    if (!$mobile) {
                        continue;
                    }
                    $sms_template='';
                    try {
                        $sms_template=$config['sms_template'];
                        $typeValue = NoticeType::getText($this->type);
                        $template = $typeValue['sms_template']['user'];
                        foreach ($this->data as $key => $value) {
                            $template = str_replace('${' . $key . '}', $value, $template);
                        }
                        Sms::send($this->saas_appid, $mobile, $sms_template, $template, $this->data);
                    } catch (\Throwable $th) {
                        Log::error("用户短信({$sms_template})通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
            if (isset($config['voice_mobile']) && $config['voice_mobile']) {
                $templateArgs=[];
                switch ($this->type) {
                    case NoticeType::ALARM['value']:
                        $templateArgs=[
                            'var1'=>$this->data['role'],
                            'var2'=>$this->data['name']
                        ];
                        break;
                        case NoticeType::WORK_ORDER['value']:
                    case NoticeType::FEEDBACK['value']:
                        break;
                    case NoticeType::ORDERS_PAY['value']:
                        $templateArgs=[
                            'var1'=>$this->data['time'],
                        ];
                        break;
                    case NoticeType::TECHNICIAN_DEPARTURE['value']:
                        $templateArgs=[
                            'var1'=>MassageReplaceIndustryPersonnelName($this->saas_appid,'技师'),
                        ];
                        break;
                    case NoticeType::TECHNICIAN_ARRIVAL['value']:
                        $templateArgs=[
                            'var1'=>MassageReplaceIndustryPersonnelName($this->saas_appid,'技师'),
                        ];
                        break;
                    case NoticeType::TECHNICIAN_VERIFICATION['value']:
                    case NoticeType::SERVICE_START['value']:
                    case NoticeType::SERVICE_END['value']:
                        break;
                    case NoticeType::REFUND['value']:
                        break;
                    case NoticeType::EXAMINE['value']:
                        break;
                    case NoticeType::TRANSFERRING['value']:
                        $templateArgs=[
                            'var1'=>$this->data['state']
                        ];
                        break;
                }
                foreach ($this->USER['mobile'] as $mobile) {
                    if (!$mobile) {
                        continue;
                    }
                    $voice_template='';
                    try {
                        $voice_template=$config['voice_template'];
                        $typeValue = NoticeType::getText($this->type);
                        $template = $typeValue['voice_template']['user'];
                        $MassageWinnerlookPrivacy=MassageWinnerlookPrivacy::getFindNumber($this->saas_appid, WinnerlookChannels::VOICE_SERVICE['value']);
                        $return_url = "{$this->domain}/app/ycMassage/Notify/winnerlook?appid={$this->saas_appid}";
                        $Yunxin=new Yunxin($this->saas_appid);
                        $data=[
                            'displayNumber' => $MassageWinnerlookPrivacy->tel,
                            'calleeNumber' => $mobile,
                            'templateID' => $voice_template,
                            'templateArgs' => $templateArgs,
                            'replayTimes'=>2,
                            'callbackUrl'=>$return_url,
                            // 'customerData'=>''
                        ];
                        $Yunxin->notify($data);
                    } catch (\Throwable $th) {
                        Log::error("用户语音({$voice_template})通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
            if (isset($config['wx']) && $config['wx']) {
                foreach ($this->USER['wx'] as $openid) {
                    if (!$openid) {
                        continue;
                    }
                    try {
                        $this->sendWx($openid, "{$this->domain}/app/ycMassage/#/?appid={$this->saas_appid}");
                    } catch (\Throwable $th) {
                        Log::error("用户微信通知失败：{$th->getMessage()}");
                        if ($this->dev) {
                            throw $th;
                        }
                    }
                }
            }
        }
    }
    public function addUSER($mobile, $openid)
    {
        $this->USER['mobile'][] = $mobile;
        $this->USER['wx'][] = $openid;
        return $this;
    }
    public function addTECHNICIAN($mobile, $openid)
    {
        $this->TECHNICIAN['mobile'][] = $mobile;
        $this->TECHNICIAN['wx'][] = $openid;
        return $this;
    }
    public function send()
    {
        $this->domain = getHpConfig('domain', (int)$this->saas_appid, 'plugins_domains');
        try {
            if (in_array('ADMIN', $this->role)) {
                $this->sendADMIN();
            }
        } catch (\Throwable $th) {
            Log::error('管理员通知失败：'.$th->getMessage());
            if ($this->dev) {
                throw $th;
            }
        }
        try {
            if (in_array('TECHNICIAN', $this->role)) {
                $this->sendTECHNICIAN();
            }
        } catch (\Throwable $th) {
            Log::error('技师通知失败：'.$th->getMessage());
            if ($this->dev) {
                throw $th;
            }
        }
        try {
            if (in_array('USER', $this->role)) {
                $this->sendUSER();
            }
        } catch (\Throwable $th) {
            Log::error('用户通知失败：'.$th->getMessage());
            if ($this->dev) {
                throw $th;
            }
        }
    }
}
